// 前端通知管理 - 简化版本
// 适用于Vue 3 Composition API

import { ref, onMounted, onUnmounted } from 'vue'
import * as signalR from '@microsoft/signalr'

// API基础URL
const API_BASE_URL = 'http://localhost:5097'

// 通知管理类
class NotificationManager {
  constructor() {
    this.connection = null
    this.isConnected = false
    this.notifications = ref([])
    this.unreadCount = ref(0)
    this.userId = 1 // 从用户状态获取
  }

  // 初始化SignalR连接
  async initSignalR() {
    try {
      console.log('正在初始化SignalR连接...')
      
      this.connection = new signalR.HubConnectionBuilder()
        .withUrl(`${API_BASE_URL}/notificationHub`)
        .withAutomaticReconnect()
        .build()

      // 监听实时通知
      this.connection.on('ReceiveNotification', (notification) => {
        console.log('收到实时通知:', notification)
        this.handleRealtimeNotification(notification)
      })

      // 连接状态变化
      this.connection.onclose(() => {
        this.isConnected = false
        console.log('SignalR连接已断开')
      })

      this.connection.onreconnected(() => {
        this.isConnected = true
        console.log('SignalR重连成功')
      })

      // 启动连接
      await this.connection.start()
      this.isConnected = true
      console.log('SignalR连接成功')
      
    } catch (error) {
      console.error('SignalR连接失败:', error)
    }
  }

  // 处理实时通知
  handleRealtimeNotification(notification) {
    // 添加到通知列表顶部
    this.notifications.value.unshift(notification)
    
    // 更新未读数量
    if (!notification.isRead) {
      this.unreadCount.value++
    }
    
    // 显示浏览器通知（可选）
    if (Notification.permission === 'granted') {
      new Notification(notification.title, {
        body: notification.content,
        icon: '/favicon.ico'
      })
    }
  }

  // 获取通知列表
  async getNotifications(pageIndex = 1, pageSize = 10, isRead = null) {
    try {
      let url = `${API_BASE_URL}/api/Notification/list?userId=${this.userId}&pageIndex=${pageIndex}&pageSize=${pageSize}`
      if (isRead !== null) {
        url += `&isRead=${isRead}`
      }

      const response = await fetch(url)
      const result = await response.json()
      
      if (result.code === 'Success') {
        this.notifications.value = result.data.pageDatas
        return result.data
      } else {
        console.error('获取通知列表失败:', result.msg)
        return null
      }
    } catch (error) {
      console.error('获取通知列表失败:', error)
      return null
    }
  }

  // 获取未读通知数量
  async getUnreadCount() {
    try {
      const response = await fetch(`${API_BASE_URL}/api/Notification/unread-count?userId=${this.userId}`)
      const result = await response.json()
      
      if (result.code === 'Success') {
        this.unreadCount.value = result.data
        return result.data
      } else {
        console.error('获取未读通知数量失败:', result.msg)
        return 0
      }
    } catch (error) {
      console.error('获取未读通知数量失败:', error)
      return 0
    }
  }

  // 标记通知为已读
  async markAsRead(notificationId) {
    try {
      const response = await fetch(`${API_BASE_URL}/api/Notification/mark-read`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          notificationId: notificationId,
          userId: this.userId
        })
      })
      
      const result = await response.json()
      
      if (result.code === 'Success') {
        // 更新本地状态
        const notification = this.notifications.value.find(n => n.id === notificationId)
        if (notification && !notification.isRead) {
          notification.isRead = true
          this.unreadCount.value--
        }
        return true
      } else {
        console.error('标记已读失败:', result.msg)
        return false
      }
    } catch (error) {
      console.error('标记已读失败:', error)
      return false
    }
  }

  // 标记所有通知为已读
  async markAllAsRead() {
    try {
      const response = await fetch(`${API_BASE_URL}/api/Notification/mark-all-read`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          userId: this.userId
        })
      })
      
      const result = await response.json()
      
      if (result.code === 'Success') {
        // 更新本地状态
        this.notifications.value.forEach(notification => {
          notification.isRead = true
        })
        this.unreadCount.value = 0
        return true
      } else {
        console.error('标记全部已读失败:', result.msg)
        return false
      }
    } catch (error) {
      console.error('标记全部已读失败:', error)
      return false
    }
  }

  // 删除通知
  async deleteNotification(notificationId) {
    try {
      const response = await fetch(`${API_BASE_URL}/api/Notification/delete`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          notificationId: notificationId,
          userId: this.userId
        })
      })
      
      const result = await response.json()
      
      if (result.code === 'Success') {
        // 从本地列表中移除
        const index = this.notifications.value.findIndex(n => n.id === notificationId)
        if (index > -1) {
          const notification = this.notifications.value[index]
          this.notifications.value.splice(index, 1)
          
          // 更新未读数量
          if (!notification.isRead) {
            this.unreadCount.value--
          }
        }
        return true
      } else {
        console.error('删除通知失败:', result.msg)
        return false
      }
    } catch (error) {
      console.error('删除通知失败:', error)
      return false
    }
  }

  // 断开连接
  disconnect() {
    if (this.connection) {
      this.connection.stop()
    }
  }
}

// Vue 3 Composition API 使用示例
export function useNotificationManager() {
  const notificationManager = new NotificationManager()
  
  // 组件挂载时初始化
  onMounted(async () => {
    await notificationManager.initSignalR()
    await notificationManager.getUnreadCount()
  })
  
  // 组件卸载时断开连接
  onUnmounted(() => {
    notificationManager.disconnect()
  })
  
  return {
    notifications: notificationManager.notifications,
    unreadCount: notificationManager.unreadCount,
    isConnected: notificationManager.isConnected,
    getNotifications: notificationManager.getNotifications.bind(notificationManager),
    getUnreadCount: notificationManager.getUnreadCount.bind(notificationManager),
    markAsRead: notificationManager.markAsRead.bind(notificationManager),
    markAllAsRead: notificationManager.markAllAsRead.bind(notificationManager),
    deleteNotification: notificationManager.deleteNotification.bind(notificationManager)
  }
}

// 使用示例
/*
<template>
  <div>
    <div>未读通知: {{ unreadCount }}</div>
    <div v-for="notification in notifications" :key="notification.id">
      <div>{{ notification.title }}</div>
      <div>{{ notification.content }}</div>
      <button @click="markAsRead(notification.id)">标记已读</button>
    </div>
  </div>
</template>

<script setup>
import { useNotificationManager } from './NotificationManager'

const {
  notifications,
  unreadCount,
  isConnected,
  getNotifications,
  getUnreadCount,
  markAsRead,
  markAllAsRead,
  deleteNotification
} = useNotificationManager()

// 获取通知列表
const loadNotifications = async () => {
  await getNotifications(1, 10)
}
</script>
*/








